﻿#include "grid.h"
#include "screen.h"

Grid::Grid(Screen* parent) :
    QGraphicsScene()
{
    p = parent;
    QGraphicsTextItem* crossid;
    addLine(0.0, 0.0, 0.0, 500.0, QPen(Qt::green, 3));
    addLine(0.0,0.0, 500.0, 0.0, QPen(Qt::green, 3));
    for(int i = 1; i <= 10; i++)
    {
        for(int j = 1; j <= 10; j++)
        {
            crossid = new QGraphicsTextItem(QString::number(j+((i-1)*10)));
            crossid->setPos((j-1)*50, (i-1)*50);
            addItem(crossid);
        }
        addLine(i*50.0, 0.0, i*50.0, 500.0, QPen(Qt::green, 3));
        addLine(0.0,i*50.0, 500.0, i*50.0, QPen(Qt::green, 3));
    }
}

void Grid::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    if(event->button() != Qt::LeftButton)
        return;

    int tempX = floor(event->scenePos().x()/50);
    int tempY = floor(event->scenePos().y()/50);
    int key = 1+tempX+tempY*10;
    if(cells.contains(key))
    {
        QString strtip = QString::fromUtf8("Gợi ý:\n");
        for(int i = 0; i < cells[key]->tips.size(); i++)
        {
            strtip.append(Tips.value(cells[key]->tips.value(i))).append("\n");
        }
        BreakTip(strtip);
        cells[key]->getChar(key, strtip);
    }
}
bool Grid::CheckMKDir(QString dirname)
{
    QDir dir;
    if(!dir.exists(dirname))
    {
        if(!dir.mkdir(dirname))
        {
            return false;
        }
    }
    return true;
}

void Grid::Save(int type, QString desc)
{
    QString filename;
    QFileDialog fileDialog;
    QDir dir;

    if(!CheckMKDir("CrossWord") || !CheckMKDir("CrossWord/Game/")
            || !CheckMKDir("CrossWord/Grid/") || !CheckMKDir("CrossWord/Draft/"))
    {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setText(QString::fromUtf8("Vui lòng kiểm tra sự tồn tại của các thư mục:\n%1/CrossWord/Grid\n%1/CrossWord/Game\n%1/CrossWord/Draft.").arg(dir.currentPath()));
        msgBox.exec();
        return;
    }
    if(type == 0)
    {
        if(gridname.isEmpty())
        {
            dir.setPath("CrossWord/Grid/");

            fileDialog.setDirectory(dir.path());
            fileDialog.setDefaultSuffix("grid");
            gridname = fileDialog.getSaveFileName(0,
                                                  "Lưu ô chử hoàn thiện",
                                                  dir.currentPath().append("/CrossWord/Grid/CWgrid%1.gird").arg(
                                                      dir.entryList(QDir::Files).size()+1),
                                                  ".grid");
        }
        filename = gridname;
    } else if (type == 1) {
        if(draftname.isEmpty())
        {
            dir.setPath("CrossWord/Draft/");

            fileDialog.setDefaultSuffix("draft");
            draftname = fileDialog.getSaveFileName(0,
                                                  "Lưu ô chử nháp",
                                                  dir.currentPath().append("/CrossWord/Draft/CWdraft%1.draft").arg(
                                                      dir.entryList(QDir::Files).size()+1),
                                                  ".draft");
        }
        filename = draftname;
    } else {
        dir.setPath("CrossWord/Game/");

        fileDialog.setDirectory(dir.path());
        fileDialog.setDefaultSuffix("game");
        filename = fileDialog.getSaveFileName(0,
                                              "Lưu game",
                                              dir.currentPath().append("/CrossWord/Game/CWsavepoint%1.game").arg(
                                                  dir.entryList(QDir::Files).size()+1),
                                              ".game");
    }

    if (filename.isEmpty()) return;

    QFile file(filename);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate))
    {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setText(QString::fromUtf8("Trục trặc khi lưu trử, kiểm tra phân quyền thư mục"));
        msgBox.exec();
        return;
    }
    //viet du lieu
    //**********************//
    QTextStream stream(&file);
    stream.setCodec("UTF-8");
    // mo ta
    if(desc.length() < 1)
    {
        stream << filename;
    } else {
        QStringList desclist = desc.split("||");
        if(desclist.size() > 1)
            stream << desclist.first() << "||" << desclist.last();
        else
            stream << desc.split("||").first();
    }
    stream << endl;
    //so luong goi y X
    stream << Tips.size();
    stream << endl;
    //cac goi y
    // key - goi y
    QMapIterator<int, QString> j(Tips);
    while (j.hasNext())
    {
        j.next();
        stream << j.key();
        stream << "<©™®>";
        stream << j.value();
        stream << "<©™®>";
        stream << endl;
    }
    //so luong N chu cai
    stream << cells.size() << endl;
    //cac chu cai
    // key - Cap - Ans - X - Y - color - N tip - tip(0)-...-tip(N)
    QMapIterator<int, Cell*> i(cells);
    while (i.hasNext())
    {
        i.next();
        stream << i.key();
        stream << "<©™®>";

        if(type > 1)
            stream << i.value()->cap->toPlainText();
        else
            stream << "";

        stream << "<©™®>";

        if(type > 1)
            stream << i.value()->ans->toPlainText();
        else
            stream << i.value()->cap->toPlainText();

        stream << "<©™®>";
        stream << i.value()->X;
        stream << "<©™®>";
        stream << i.value()->Y;
        stream << "<©™®>";
        stream << i.value()->colorname;
        stream << "<©™®>";
        stream << i.value()->tips.size();
        stream << "<©™®>";
        for(int j = 0; j < i.value()->tips.size(); j++)
        {
            stream << i.value()->tips.value(j);
            stream << "<©™®>";
        }
        stream << endl;
    }
    //**********************//
    //ket thuc phan viet
    file.close();

    QMessageBox msgBox;
    msgBox.setIcon(QMessageBox::Information);
    msgBox.setText(QString::fromUtf8("Lưu hoàn tất: ").append(filename));
    msgBox.exec();
}

void Grid::Load(QString filename)
{
    Clean();
    bool type = false;
    if(filename.isEmpty())
    {
        type = true;
    }

    if(type)
    {
        filename = QFileDialog::getOpenFileName();
        if ( filename.isEmpty() ) return;

        QFileInfo fileinfo(filename);

        if(fileinfo.suffix() == "grid")
            gridname = filename;
        else if(fileinfo.suffix() == "draft")
            draftname = filename;
    }
    QFile file(filename);

    if (!file.open( QIODevice::ReadOnly ))
    {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setText(QString::fromUtf8("Không thể mở file!"));
        msgBox.exec();
        return;
    }

    //doc du lieu
    //**********************//
    QTextStream stream(&file);
    stream.setCodec("UTF-8");
    //mo ta
    //giai quyet rac roi chap va
    //interface??
    if(!type)
    {
        PlayScreen* ps = (PlayScreen*) p;
        ps->descLabel->setText(stream.readLine());
    }else{
        EditScreen* es = (EditScreen*) p;
        es->inputName->setText(stream.readLine());
    }
    //X goi y
    int X = stream.readLine().toInt();
    for(int i = 0; i < X; i++)
    {
        QStringList tipline = stream.readLine().split("<©™®>");
        Tips.insert(tipline.value(0).toInt(), tipline.value(1));
    }
    //N chu cai
    int N = stream.readLine().toInt();
    for(int i = 0; i < N; i++)
    {
        QStringList cellline = stream.readLine().split("<©™®>");
        QColor color(cellline.value(5));
        color.setAlpha(140);
        Cell* cell = new Cell(cellline.value(3).toInt(), cellline.value(4).toInt(), color);
        cell->ans->setPlainText(cellline.value(2));
        for(int j = 1; j <= cellline.value(6).toInt(); j++)
        {
            cell->tips.append(cellline.value(6+j).toInt());
        }
        addItem(cell->rect);
        addItem(cell->cap);
        cells.insert(cellline.value(0).toInt(), cell);

        if(!type)
        {
            cell->cap->setPlainText(cellline.value(1));
            addItem(cell->ans);
            QString tooltip;
            for(int j = 1; j <= cellline.value(6).toInt(); j++)
            {
                tooltip.append(Tips.value(cellline.value(6+j).toInt())).append("\n");

            }
            BreakTip(tooltip);
            cell->rect->setToolTip(tooltip);
        }else{
            cell->cap->setPlainText(cellline.value(2));
        }
    }
    //**********************//
    file.close();
    if(!type)
    {
        isPlaying = true;
        this->sender()->parent()->deleteLater();
    }
    p->buttonSave->setDisabled(false);
    p->buttonDone->setDisabled(false);
}
void Grid::Clean()
{
    QMapIterator<int, Cell*> i(cells);
    while (i.hasNext())
    {
        i.next();
        i.value()->~Cell();
    }
    cells.clear();
    Tips.clear();
    gridname.clear();
    draftname.clear();
    isPlaying = false;
}

void Grid::BreakTip(QString& str)
{
    int i = 0;
    int leng = str.length();
    if(leng <= 50) return;

    while(true)
    {
        i = str.indexOf(" ", i + 50);
        if(i < 0) return;

        str.replace(i, 1, "\n");
    }
}
